package collection.set;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {

    /*
    * TreeSet 中添加的数据,要求必须是相同的类的对象(为了可以进行比较操作)
    *
    * TreeSet的两种排序方式:自然排序和定制排序
    *   1:自然排序:比较两个对象是否相同的标准,compareTo()返回0,不在是equals();
    *   2:定制排序:比较两个对象是否相同的标准,compare()返回0,不在是equals();
    *
    * */
    @Test
    public void test1(){
        TreeSet set = new TreeSet();

        set.add(123);
        set.add(35);
        set.add(2345);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test2(){
        TreeSet set = new TreeSet();

        set.add(new User("tom",12));
        set.add(new User("aom",12));
        set.add(new User("jerry",9));
        set.add(new User("john",23));
        set.add(new User("john",43));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test3(){
        TreeSet set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o, Object t1) {
                if (o instanceof User && t1 instanceof User){
                    User u1 = (User)o;
                    User u2 = (User)t1;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }else{
                    throw new RuntimeException("输入的类型不匹配");
                }
            }
        });

        set.add(new User("tom",12));
        set.add(new User("aom",12));
        set.add(new User("jerry",9));
        set.add(new User("john",23));
        set.add(new User("john",43));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}
